import 'package:flutter/material.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/ui/goods/goods_home_viewmodel.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/utils/xfg_utils.dart';
import 'package:gold/widgets/oval_image.dart';
import 'package:gold/widgets/xfg_text.dart';

/// @description: 商品首页
/// @author tangzhentao
/// @created at 21:38 2024/11/25

class GoodsHomePage extends StatefulWidget {
  const GoodsHomePage({super.key});

  @override
  State<StatefulWidget> createState() => _GoodsHomeState();
}

class _GoodsHomeState extends State<GoodsHomePage> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidget<GoodsHomeViewmodel>(
        model: GoodsHomeViewmodel(),
        onInit: (data) => data.loadFirst(),
        toplessBuilder: (_, home) => Column(
          children: [
            /// 顶部标题及搜索
            Container(
              height: XfgSize().size67 + XfgSize().statusBarHeight + kToolbarHeight,
              padding: EdgeInsets.only(top: XfgSize().statusBarHeight),
              decoration: const BoxDecoration(gradient: XfgColor.goodsHomeGradient),
              child: Column(
                children: [
                  Container(
                    height: kToolbarHeight,
                    alignment: Alignment.center,
                    child: XfgText('商品', fontSize: XfgSize().text20, color: XfgColor.white, bold: FontWeight.w500),
                  ),
                  Expanded(
                    child: Align(
                      alignment: Alignment.center,
                      child: Container(
                        height: XfgSize().size38,
                        width: XfgSize().size352,
                        padding: EdgeInsets.only(left: XfgSize().size18, right: XfgSize().size4),
                        decoration: BoxDecoration(color: XfgColor.white, borderRadius: BorderRadius.circular(XfgSize().size38)),
                        child: Row(
                          children: [
                            OvalImage(Res.imagesIntegralSearch, size: Size.square( XfgSize().size14)),
                            Expanded(
                              child: TextField(
                                style: TextStyle(fontSize: XfgSize().text16, color: XfgColor.text1D),
                                controller: home.editingController,
                                focusNode: home.foucsNode,
                                decoration: InputDecoration(
                                  isDense: true,
                                  isCollapsed: true,
                                  border: InputBorder.none,
                                  contentPadding: EdgeInsets.only(left: XfgSize().size8),
                                  hintText: '商品名称',
                                  hintStyle: TextStyle(fontSize: XfgSize().text16, color: XfgColor.text2),
                                ),
                              ),
                            ),
                            GestureDetector(
                              onTap: home.search,
                              child: Container(
                                  width: XfgSize().size60,
                                  height: XfgSize().size30,
                                  alignment: Alignment.center,
                                  decoration: BoxDecoration(color: XfgColor.red, borderRadius: BorderRadius.circular(XfgSize().size30)),
                                  child: XfgText(' 搜索商品', fontSize: XfgSize().text10, color: XfgColor.white)
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
            /// 排序
            Container(
              margin: EdgeInsets.only(bottom: XfgSize().size2),
              height: XfgSize().size40,
              child: Builder(builder: (ctx) {
                final sales = ctx.select<GoodsHomeViewmodel, int>((k) => k.sales);
                final price = ctx.select<GoodsHomeViewmodel, int>((k) => k.price);
                return Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: home.setDefault,
                        child: Center(child: XfgText('综合', fontSize: XfgSize().text14, color: sales == 0 && sales == 0 ? XfgColor.theme:XfgColor.text2, bold: FontWeight.w500)),
                      ),
                    ),
                    _itemSortWidget('销量排序', sales, onTap: home.changeSales),
                    _itemSortWidget('价格排序', price, onTap: home.changePrice)
                  ],
                );
              }),
            )
          ],
        ),
        builder: (ctx, home) => Padding(
          padding: EdgeInsets.symmetric(horizontal: XfgSize().size10),
          child: MediaQuery.removePadding(
            context: ctx,
            removeTop: true,
            removeBottom: true,
            child: SmartRefresher(
              controller: home.controller,
              enablePullUp: true,
              enablePullDown: true,
              onRefresh: () => home.refresh(),
              onLoading: () => home.loadMore(),
              child: WaterfallFlow.builder(
                  gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2, mainAxisSpacing: XfgSize().size10, crossAxisSpacing: XfgSize().size10
                  ),
                  itemCount: home.goodsList.length,
                  itemBuilder: (_, index) {
                    final goods = home.goodsList[index];
                    final reward = '${goods.rewardPoints?.replaceAll('.00', '')?? ''}积分';
                    final prices = goods.price?.split(('.'));
                    return GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        final id = goods.id;
                        if (id != null) {
                          XfgNav.pushNamed(Routes.goodsDetail, arguments: id);
                        } else {
                          '商品信息缺失'.toast();
                        }
                      },
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(XfgSize().size6),
                        child: Container(
                          color: XfgColor.white,
                          child: Column(
                            children: <Widget>[
                              HttpImage(goods.coverImage, size: Size(double.infinity, XfgSize().size175)),
                              Container(
                                padding: EdgeInsets.all(XfgSize().size10),
                                alignment: Alignment.centerLeft,
                                child: XfgText(goods.name?? '', fontSize: XfgSize().text14, color: XfgColor.text1, maxLines: 2, overflow: TextOverflow.ellipsis),
                              ),
                              Padding(
                                padding: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size2, XfgSize().size10, XfgSize().size12),
                                child: Row(
                                  children: [
                                    Expanded(child: XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.theme, children: [
                                      TextSpan(text: '${prices?.first?? ''}.', style: TextStyle(fontSize: XfgSize().text20)),
                                      TextSpan(text: prices?.last?? '')
                                    ])),
                                    Container(
                                      decoration: BoxDecoration(border: Border.all(color: XfgColor.theme, width: XfgSize().size0_5), borderRadius: BorderRadius.circular(XfgSize().size2)),
                                      width: XfgSize().size12 + xfgBoundingTextSize(reward, style: TextStyle(fontSize: XfgSize().text12)).width,
                                      height: XfgSize().size18,
                                      alignment: Alignment.center,
                                      child: XfgText(reward, fontSize: XfgSize().text12, color: XfgColor.theme),
                                    )
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    );
                  }
              ),
            ),
          ),
        )
    );
  }

  /// 排序
  Widget _itemSortWidget(String text, int sort, {GestureTapCallback? onTap}) => Expanded(
    child: GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          XfgText(text, fontSize: XfgSize().text14, color: sort ==1 || sort == 2 ? XfgColor.theme:XfgColor.text2, bold: FontWeight.w500),
          Icon(sort == 2 ? Icons.arrow_upward_rounded:Icons.arrow_downward_sharp, size: XfgSize().size16, color: sort ==1 || sort == 2 ? XfgColor.theme:XfgColor.text1D)
        ],
      ),
    ),
  );

  @override
  bool get wantKeepAlive => true;

}
